"use strict";
const path = require("path");
const fs = require("fs");
const rootDir = __dirname;

let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let numUnit = ["", "十", "百", "千", "万"];
let chapterUnit = [0, 0, "章", "条"];

const toChinesNum = (num) => {
	// num = parseInt(num);
	let getWan = (temp) => {
		let strArr = temp.toString().split("").reverse();
		let newNum = "";
		for (var i = 0; i < strArr.length; i++) {
			newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? numUnit[0] : numUnit[i]))) + newNum;
		}
		return newNum.replace(/^一十/, "十");
	}
	let overWan = Math.floor(num / 10000);
	let noWan = num % 10000;
	if (noWan.toString().length < 4) {
		noWan = "0" + noWan;
	}
	return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}

const modifyHelpers = [
	{
		description: "修订换行符",
		pattern: /(\r?\n){2,}/igm,
		replacement: "$1$1",
	},
	{
		description: "修改章号",
		pattern: /^第[一二三四五六七八九十]+章\s*/igm,
		replacement: "## ",
	},
	{
		description: "修改条号",
		pattern: /^第[一二三四五六七八九十]+条\s*/igm,
		replacement: "### ",
	},
	// {
	// 	description: "添加章节号",
	// 	pattern: /^(#+)\s+/igm,
	// 	replacement: function (s, key) {
	// 		const length = key.length
	// 		return chapterUnit[length]
	// 			? "第" + toChinesNum(this.indexHelper[length]++) + chapterUnit[length] + " "
	// 			: s

	// 	},
	// },
	{
		description: "修改大序号",
		pattern: /^[（(]([一二三四五六七八九十]+)[)）]\s*/igm,
		// replacement: "（$1）",
		replacement: "1. ",
	},
	{
		description: "修改小序号 -- （1）",
		pattern: /^（\d+）\s*/igm,
		replacement: "	1. ",
	},
	{
		description: "修改小序号 -- 1、",
		pattern: /^\d+、\s*/igm,
		replacement: "	1. ",
	},
]
class Doc {
	constructor(fileName) {
		this.fileName = fileName;
		this.indexHelper = [
			0,
			0,
			1,
			1,
		];
	}
	inspect() {
		return this.fileName
	}
	get stack() {
		return this.inspect();
	}
	async open() {
		this.contents = (await fs.readFileSync(this.fileName)).toString();
	}
	async save() {
		return fs.writeFileSync(this.fileName, this.contents);
	}
	async modify() {
		const doc = this;
		await doc.open();
		console.log("正在修订:", doc.fileName);
		modifyHelpers.forEach(
			modifyHelper => {
				console.log(modifyHelper.description);
				var replacement = modifyHelper.replacement;
				if (replacement.bind) {
					replacement = replacement.bind(doc);
				}
				doc.contents = doc.contents.replace(modifyHelper.pattern, replacement);
			}
		);
		await doc.save();
	}
}

const modifyDir = async (dir) => {
	var docs = await fs.readdirSync(dir);
	docs = docs.filter(
		fileName => /\.(md|markdown)$/i.test(fileName)
	).map(
		fileName => new Doc(path.resolve(dir, fileName))
	);
	await Promise.all(
		docs.map(doc => doc.modify())
	);
	return docs;
}

(async () => {
	await modifyDir(rootDir);
	await modifyDir(path.join(rootDir, "规约文本"));
	await modifyDir(path.join(rootDir, "规约文本/示范文本使用说明"));
})()
